// Author: Ivan Chau
package uk.ac.cam.kcic2.scene;

import java.util.ArrayList;

import uk.ac.cam.kcic2.math.Params;
import uk.ac.cam.kcic2.math.Transform;
import uk.ac.cam.kcic2.math.Vector3D;

public class Plane extends Primitives {

	// plane does not need any transformations and parents, point is bottom left corner of plane
	public Plane(ArrayList<Transform> trans, ColourCoeffs coeffs, CompoundObject father){
		super(trans, coeffs, father);
	}
/*
	public Plane(ColourCoeffs coeffs, Vector3D normal, Vector3D point) {
		super(null, coeffs, null);
		planeNormal = normal.normalize();
		planePoint = point;
	}
*/
	@Override
	public IntersectionInfo getIntersection(Ray eye) {
		// transform the world ray to the plane's local coordinates
		Vector3D localRayOrigin = worldToLocalPointTransform.mult(eye.origin);
		Vector3D localRayDirection = worldToLocalNormalTransform.mult(eye.direction);
		// find the only t;
		double t = -normal.dot(localRayOrigin)/normal.dot(localRayDirection);

		IntersectionInfo intersection = null;
		if (t < Double.POSITIVE_INFINITY && t > Params.EPILSON){
			// find the intersecting point and the unit surface normal in 
			// world coordinates
			Vector3D localIntersectPoint = localRayOrigin.plus(localRayDirection.mult(t));
			if (localIntersectPoint.x >= 0 && localIntersectPoint.x <= 1 && 
					localIntersectPoint.y >= 0 && localIntersectPoint.y <= 1){
				Vector3D localSurfaceNormal = normal;
				boolean inwards = true;
				if (localRayOrigin.z < 0){
					localSurfaceNormal = normal.mult(-1);
					inwards = false;
				}
				
				Vector3D worldIntersectPoint = localToWorldPointTransform.mult(localIntersectPoint);
				Vector3D worldSurfaceNormal = localToWorldNormalTransform.mult(localSurfaceNormal).normalize();
				//System.err.println(worldSurfaceNormal.x + " " + worldSurfaceNormal.y + " " + worldSurfaceNormal.z);
				intersection = new IntersectionInfo(t, worldIntersectPoint, worldSurfaceNormal, this, inwards);
			}
		}

		return intersection;
	}

}
